package com.ly.utils;

import com.ly.entity.BankAccount;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Author: LiYao
 * CreateTime: 2025-03-11 19:37
 * Description:
 * Version: 1.0
 */
public class IOUtil {

    private static Scanner scanner = new Scanner(System.in);
    // 工具方法
    public static String getInput(String prompt) {
        System.out.print(prompt);
        return scanner.nextLine();
    }

    public static int getIntInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                int input = Integer.parseInt(scanner.nextLine());
                return input;
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入数字！");
            }
        }
    }

    public static double getDoubleInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                return Double.parseDouble(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入有效金额！");
            }
        }
    }






    // 将账户信息写入文件
    public static void writeAccountsToFile(List<BankAccount> accounts, String fileName)  {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            for (BankAccount account : accounts) {
                writer.write(account.getAccountID() + " " + account.getPassword() + " " + account.getBalance());
                writer.newLine();
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    // 从文件读取账户信息
    public static ArrayList<BankAccount> readAccountsFromFile(String fileName)  {
        ArrayList<BankAccount> accounts = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(" ");
                if (parts.length == 3) {
                    String id = parts[0];
                    String password = parts[1];
                    double balance = Double.parseDouble(parts[2]);
                    accounts.add(new BankAccount(id, password, balance));
                }
            }
        }catch(IOException e) {
            throw new RuntimeException(e);
        }
        return accounts;
    }


}
